<template>
    <!-- 我的作品 - 列表页 -->
    <!-- v-show="isShow" -->
    <div v-show="isShow" text="加载中..." class="work_list">
        <div class="work_listIns">
            <div class="work_pic">
                <!-- <img :src="imgUrl" alt=""> -->
                <!-- <img src="http://www.gzrbxmt.com:9001/images/common/0a560fa0-cc00-11ea-9199-4f212e5ee595.png" alt=""> -->
                 <img src="../../src/images/logo.png" alt="">
            </div>
            <div class="work_audio">
                <div class="work_audio_top">
                    <div class="left">
                        <!-- <p class="music_name">{{audioData.display_name}}</p> -->
                        <p>{{audioData.prompt}}</p>
                        <p class="username">by {{userState.nickname}}</p>
                    </div>
                    <div v-if="showDel" class="right">
                        <button></button>
                        <button class="del" @click="dialogVisible = true"></button>
                    </div>
                </div>
                <div class="work_audio_center_warp">
                    <!-- <div v-if="audioData.lyric" class="lyric_area">
                        <textarea name="" id="" :value="audioData.lyric"></textarea>
                    </div>
                    <div v-if="!audioData.lyric" class="lyric_area">
                        纯音乐
                    </div> -->
                    <div class="work_audio_center" ref="waveform">
                        <!-- 这里显示音轨 -->
                    </div>
                </div>
                
                <div class="work_audio_bottom">
                    <div class="work_audio_bottom_left">
                        <button @click="togglePlay" :class="{'play': isPlay}">
                            <span v-show="!isPlay">播放</span>
                            <span v-show="isPlay">暂停</span>
                        </button>
                        <button @click="like" :class="{'like': isLike}">收藏</button>
                        <button class="download" @click="downloadAudio">下载</button>
                        <button v-if="showDel" class="rename" @click="dialogFormVisible = true">重命名</button>
                    </div>
                    <div class="work_audio_bottom_right">
                        {{ formatTime(currentTime) }} / {{ formatTime(duration) }}
                    </div>
                    
                </div>

            </div>
        </div>

        <el-dialog
            v-model="dialogVisible"
            title="提示"
            width="500"
            :show-close="false"
            :modal="true"
            align-center
        >
            <span>您确认删除这首歌吗？</span>
            <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="delMusic(musicId)">
                确认
                </el-button>
            </div>
            </template>
        </el-dialog>


        <el-dialog 
            v-model="dialogFormVisible" 
            title="重命名" 
            width="500" 
            :show-close="false"
            align-center
            >
            <el-input v-model="resetName" autocomplete="off" />
            <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="rename(musicId)">确认</el-button>
            </div>
            </template>
        </el-dialog>

    </div>
    </template>
    
    <script setup>
    import { ref, onMounted, onUnmounted, watch, inject, computed } from 'vue'
    import WaveSurfer from 'wavesurfer.js'
    import { useUserStore } from '../store/user';
    import { saveAs } from 'file-saver';
    import { ElMessageBox } from 'element-plus';

    const { userState } = useUserStore()
    const props = defineProps(['audioSrc', 'playIndex', 'musicId', 'auidoImg', 'audioData', 'showDel'])
    const emit = defineEmits(['play', 'like', 'isCreateFinish'])
    // const href = ref(audioUrl.value)
    console.log(props.audioData)
    const isPlay = ref(false)
    const isLike = ref(false)
    const waveform = ref(null)
    let wavesurfer = null
    let isShow = ref(false)
    let duration = ref(0);
    let currentTime = ref(0)
    let resetName = ref(props.audioData.display_name)

    let dialogFormVisible = ref(false)
    let dialogVisible = ref(false)

    const imgUrl = ref(props.audioData.image_url)
    const audioUrl = ref (props.audioData.audio_url)

    const formLabelWidth = '140px'
    // console.log('imgUrl:', imgUrl.value)   // 可以打印出 imgUrl: https://cdn2.suno.ai/image_c8c61ed7-b70e-4dbe-a431-b97c72d5a993.jpeg
    // console.log('audioUrl:', audioUrl.value)  // 可以打印出 audioUrl: https://cdn1.suno.ai/c8c61ed7-b70e-4dbe-a431-b97c72d5a993.mp3
    
    const finish = inject('createFinish')
    
    watch(
        () => isShow,
        (val) => {
            console.log('音乐制作完成', val)
            if(val) {
                console.log('音乐制作完成')
                emit('isCreateFinish','音乐制作完成')
            }
        },
        // { immediate: true }
    );
    watch(
        () => userState.playIndex,
        newVal => {
            // console.log('userState.playIndex变了', newVal)
            if ( newVal ===  props.playIndex) {
                wavesurfer.play()
            } else {
                wavesurfer.pause()
            }
        }
    )
    
    function rename(id) {
        dialogFormVisible.value = false
        userState.musicList.forEach(item => {
            if (item.id === id) {
                item.display_name = resetName.value
            }
        })
    }

    // 删除歌曲
    function delMusic(id) {
        dialogVisible.value = false
        console.log(id)
        userState.musicList = userState.musicList.filter(item => item.id !== id);
    }

    function formatTime(seconds) {
        const minutes = Math.floor(seconds / 60);
        const secs = Math.floor(seconds % 60);
        return `${minutes}:${secs < 10 ? "0" : ""}${secs}`;
    }

    // 下载音频
    function downloadAudio() {
        const audioUrl = props.audioData.audio_url;
        console.log('音频URL:', audioUrl);

        // 检查 audioUrl 是否有效
        if (typeof audioUrl === 'string' && audioUrl.trim() !== '') {
            fetch(audioUrl)
            .then(res => res.blob())
            .then(blob => {
                // 从 URL 中提取文件名并保存
                saveAs(blob, audioUrl.split('/').pop());
            })
            .catch(err => {
                console.error('下载音频失败:', err);
            });
        } else {
            console.error('无效的音频URL:', audioUrl);
        }
    }
    
    // 播放/暂停音频
    function togglePlay() {

        emit('play')

        emit('showLyric', props.audioData.lyric?props.audioData.lyric:'instrumental' )
        
        if (wavesurfer && wavesurfer.isPlaying()) {
            wavesurfer.pause()
            isPlay.value = false
        } else if (wavesurfer) {
            wavesurfer.play()
            isPlay.value = true
        }
    }
    
    // 收藏
    function like() {
        // console.log(props.audioData.id)
        const likeId = props.audioData.id
        isLike.value = !isLike.value
        emit('like', {id: likeId, like: isLike.value})
    }
    
    // 初始化 WaveSurfer
    onMounted(() => {
        wavesurfer = WaveSurfer.create({
            container: waveform.value,
            waveColor: '#d3d3d3',
            progressColor: '#bfa0f1',
            barWidth: 2,
            barHeight:1,
            sampleRate: 7000,
            // splitChannels: true,
            // normalize:true,
            bargap:5,
            height: 100,
            backend: 'MediaElement',
        })
    
        // 监听音频状态
        wavesurfer.on('play', () => {
            isPlay.value = true
        })
    
        wavesurfer.on('pause', () => {
            isPlay.value = false
        })

        
        wavesurfer.on('error', (error) => {
            console.error("WaveSurfer decoding error:", error);
        });

        wavesurfer.on("audioprocess", () => {
            currentTime.value = wavesurfer.getCurrentTime();
        });


        // 监听音频加载成功
        wavesurfer.on('ready', () => {
            console.log('音频加载成功！')
            duration.value = wavesurfer.getDuration();
            finish()
            isShow.value = true
            // 可以在这里执行加载完成后的操作
            isPlay.value = false  // 默认不播放
        })
    
        // 加载音频文件
        if (audioUrl.value) {
            wavesurfer.load(audioUrl.value)
            // console.log(wavesurfer)
        }
    })
    
    // 销毁 WaveSurfer 实例
    onUnmounted(() => {
        if (wavesurfer) {
            // wavesurfer.destroy()
            // wavesurfer = null
        }
    })
    
    // 监听音频路径的变化
    watch(() => audioUrl.value, (newSrc) => {
        if (newSrc && wavesurfer) {
            wavesurfer.load(newSrc)
            isPlay.value = false
        }
    })
    </script>
    
    <style scoped>
    .work_list {
      width: 98%;
      border-radius: 10px;
      overflow: hidden;
      background-color: #40414f;
    }
    
    .work_list .work_listIns {
      height: 192px;
      width: 100%;
      display: flex;
      flex-direction: row;
      justify-content: start;
      align-items: start;
      border-radius: 5px;
      overflow: hidden;
    }
    
    .work_pic{
      width: 198px;
      height: 100%;
      background-color: #2b2b3f;
      text-align: center;
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
    }
    .work_pic img {
      /* width: 100%; */
      height: 40%;
    }
    .work_audio{
      height: 100%;
      background: linear-gradient(180deg, rgba(45, 46, 67, 1) 0%, rgba(67, 69, 81, 1) 100%);;
      flex:1;
      padding-left: 20px;
    }
    
    .work_audio_top {
        width: 100%;
        height: 40px;
        line-height: 40px;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        gap: 10px;
        padding-right: 20px;
        box-sizing: border-box;
    }

    .work_audio_top .left {
        display: flex;
        gap: 10px;
    }

    .work_audio_top .music_name {
        color: #FFF;
        margin-right: 20px;
    }

    .work_audio_top .right {
        display: flex;
    }

    .work_audio_top .right .del {
        width: 24px;
        height: 24px;
        background: url(../images/icon_del.png) no-repeat center;
        background-size: 80%;
    }
    
    .work_audio_top p {
        font-size: 16px;
        color: #515a63;
    }
    
    .work_audio_top .username {
        color: #999;
        margin-left: 20px;
    }

    .work_audio_center_warp {
        width: 100%;
        height: 98px;
        
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        align-items: center;
    }

    .lyric_area {
        width: 150px;
        height: 100%;
        overflow: scroll;
        font-size: 14px;
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        font-size: 14px;
        color: #FFF;
    }
    .lyric_area textarea {
        width: 100%;
        height: 100%;
        background-color: none;
        background: none;
        color: #FFF;
        border: none;
    }
    
    .work_audio_center {
        height: 100%;
        padding-right: 20px;
        box-sizing: border-box;
        flex: 1;
    }
    
    .work_audio_bottom {
        width: 100%;
        height: 54px;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        color: #FFF;
    }

    .work_audio_bottom_left {
        width: 70%;
        height: 100%;
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        align-items: center;
        gap: 10px;
    }

    .work_audio_bottom_left .rename {
        padding-left: 0;
        text-align: center;
    }
    
    .work_audio_bottom button, .download {
        width: 86px;
        height: 42px;
        line-height: 42px;
        background-color: #FFF;
        border: 1px solid #636363;
        border-radius: 5px;  
        text-align: left;
        padding-left: 34px; 
        font-size: 14px;
        display: block;
        box-sizing: border-box;
    }

    .download{
        text-decoration: none;
        color: #515a63;
    }

    
    .work_audio_bottom button:nth-child(1) {
        background:#FFF url(../images/work_play.png) no-repeat 15px center;
        background-size: 18%;
    }
    
    .work_audio_bottom button.play:nth-child(1) {
        background:#FFF url(../images/work_stop.png) no-repeat 15px center;
        background-size: 20%;
    }
    
    .work_audio_bottom button:nth-child(2) {
        background:#FFF url(../images/work_heart.png) no-repeat 15px center;
        background-size: 20%;
    }
    
    .work_audio_bottom button.like:nth-child(2) {
        background:#FFF url(../images/work_heart_red.png) no-repeat 15px center;
        background-size: 20%;
    }
    
    .work_audio_bottom .download{
        background:#FFF url(../images/work_download.png) no-repeat 15px center;
        background-size: 20%;
    }

    .work_audio_bottom_right {
        font-size: 14px;
        padding-right: 20px;
    }

    .el-input__wrapper .el-input__inner {
        color: #333 !important;
    }

    :deep(.el-input__wrapper) {
        color: #333 !important;
    }
    :deep(.el-input__inner) {
        color: #333 !important;
    }
    </style>
    